package com.run.cat.common.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 绫诲悕: MyBeanUtils
 * 浣滅敤璇存槑: 瀵硅薄宸ュ叿绫�
 * 鍒涘缓鏃堕棿: 2015骞�10鏈�23鏃� 涓嬪崍2:49:40
 *
 * @author zygh
 * @since JDK 1.8
 */
public class MyBeanUtils extends BeanUtils {
    /**
     * 鏂规硶浣滅敤璇存槑:getDeclaredField
     * 浣跨敤璇存槑:鏍规嵁鏂规硶鍚嶈幏鍙栧璞′腑鐨勬柟娉�
     * 浣跨敤娉ㄦ剰浜嬮」:
     *
     * @param object       瀵硅薄
     * @param propertyName 鏂规硶鍚�
     * @return 鏂规硶瀵硅薄
     * @throws NoSuchFieldException 鏈壘鍒版柟娉曞紓甯�
     * @author zygh
     * @since JDK 1.8
     */
    public static Field getDeclaredField(Object object, String propertyName) throws NoSuchFieldException {
        Assert.notNull(object);
        Assert.hasText(propertyName);
        return getDeclaredField(object.getClass(), propertyName);
    }

    /**
     * 鏂规硶浣滅敤璇存槑:copyBean
     * 浣跨敤璇存槑: 澶嶅埗涓�涓璞�
     * 浣跨敤娉ㄦ剰浜嬮」:
     *
     * @param ori 鍘熷璞�
     * @param cls 鐩爣瀵硅薄class
     * @param <T> 娉涘瀷
     * @return 澶嶅埗鍚庣殑鏂板璞�
     * @author zygh
     * @since JDK 1.8
     */
    public static <T> T copyBean(Object ori, Class<T> cls) {
        if (ori instanceof LinkedHashMap) {
            return new JSONObject((LinkedHashMap) ori).toJavaObject(cls);
        }
        T obj = BeanUtils.instantiate(cls);
        BeanUtils.copyProperties(ori, obj);
        return obj;
    }

    public static <T> List<T> copyArrayBean(Object ori, Class<T> cls) {
        List<T> newArray = new ArrayList<>();
        if (ori instanceof ArrayList) {
            List<?> oriList = (List<?>) ori;
            for (Object object : oriList) {
                newArray.add(copyBean(object,cls));
            }
        }
        return newArray;
    }

    /**
     * 鏂规硶浣滅敤璇存槑:copyBeanList
     * 浣跨敤璇存槑: 鎵归噺澶嶅埗瀵硅薄
     * 浣跨敤娉ㄦ剰浜嬮」:
     *
     * @param oriList 鍘熷璞￠泦鍚�
     * @param cls     鐩爣瀵硅薄
     * @param <T>     娉涘瀷
     * @return 鏂板鍒剁殑瀵硅薄闆嗗悎
     * @author zygh
     * @since JDK 1.8
     */
    public static <T> List<T> copyBeanList(List<?> oriList, Class<T> cls) {
        List<T> tList = new ArrayList<>();
        for (Object obj : oriList) {
            T t = copyBean(obj, cls);
            tList.add(t);
        }
        return tList;
    }

}
